<template>
  <van-field
    :model-value="selectValue"
    readonly
    :label="title"
    :placeholder="`请选择${title}`"
    @click-input="clickSelectDate"
  >
    <template #button>
      <slot name="button"></slot>
    </template>
  </van-field>

  <van-popup
    v-model:show="visible"
    position="bottom"
  >
    <van-picker
      :title="title"
      :columns="list"
      @cancel="clickCancel"
      @confirm="clickConfirm"
    />
  </van-popup>
</template>

<script setup>
import { computed, toRefs, ref } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  list: {
    type: Array,
    default: [],
  },
  title: {
    type: String,
    default: ''
  }
})
const emits = defineEmits(['update:modelValue', 'confirm'])

const visible = ref(false)

const selectValue = computed(() => {
  const { modelValue, list } = toRefs(props)

  const item = list.value.find(val => val.value == modelValue.value)
  if (item) return item.text
  return ''
})

function clickSelectDate () {
  visible.value = true
}
function clickCancel () {
  visible.value = false
}
function clickConfirm ({ selectedOptions }) {
  emits('update:modelValue', selectedOptions[0].value)
  emits('confirm', { value: selectedOptions })
  clickCancel();
}

defineExpose({ clickSelectDate })
</script>